package com.huawei.classroom.student.h60;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ChatClient {
	private Socket socket;
	private PrintWriter out = null;
	private BufferedReader in = null;
	private boolean judge = false;//判断是否登录成功
	 /**
	  * 根据情况适当抛出异常 
	  * @param ip
	  * @param port
	  */
	public ChatClient (String ip, int port) {
		try {
			socket = new Socket(ip, port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 登录,成功返回true，否则返回false，根据情况适当抛出异常 
	 * 
	 * @param userName
	 * @param password
	 * @return
	 * @throws IOException 
	 */
	public boolean login(String userName,String password) throws IOException {
		for(int i=0; i<ChatServer.user.length; i++) {
			String[] mess = ChatServer.user[i].split("\t");
			if(userName.equals(mess[0]) && password.equals(mess[1])) {//登录成功就给流
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				out = new java.io.PrintWriter(socket.getOutputStream());
				judge = true;
				return judge;	
			}
		}
		judge = false;
		return judge;
	}
	/**
	 * 退出，根据情况适当抛出异常 
	 * @throws IOException 
	 */
	public void logout() throws IOException {
		out.write("BYE"+"\r\n");//记得得加后面的换行，这里卡了我好久艹
		out.flush();
		out.close();
		in.close();
		judge = false;
	}
	/**
	 * 发言, 只有登录以后才能发言， 根据情况适当抛出异常 
	 * 如果没有登录 抛出异常
	 *  
	 * @param str
	 * @throws Exception 
	 */
	public void speak(String str) throws Exception {
		 if(judge) {
			 out.write(str+"\r\n");
			 out.flush();
		 }else {
			 throw new Exception("not login");
		 }
	}
	/**
	 * 读取聊天室目前的发言，根据情况适当抛出异常 
	 * 只有登录以后才可以读到,否则返回null
	 * 得到聊天室里面所有的发言（包括自己的），如果此时没有发言则立刻返回null，否则每次调用read的时候按队的方式返回一个句话
	 * @throws IOException 
	 */
	public String read() throws IOException {
		if(!judge)
		return null;
		String myread = in.readLine();
		//System.out.println(myread);
		return myread;
	}
	
}
